import { createRouter, createWebHashHistory } from 'vue-router';
import { ROOT_ROUTE, LOGIN_ROUTE, NOTFOUND_ROUTE } from './routes';
import useUserStore from '@/stores/user';

const router = createRouter({
    history: createWebHashHistory(),
    routes: [ROOT_ROUTE, LOGIN_ROUTE, NOTFOUND_ROUTE]
});

const NO_LOGIN_ROUTES: string[] = [
    '/404'
];

// 全局前置守卫-路由拦截
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const loginPath = '/login'

    // 判断是否需登录
    if (NO_LOGIN_ROUTES.includes(to.path)) {
        next()
    } else if (userStore.token) {
        if (userStore.routers.length) {
            next()
        } else {
            //权限处理 动态加载路由
            await userStore.getAuthMenusFn();

            // 初始化默认跳转
            ROOT_ROUTE.redirect = '/home'
            router.addRoute(ROOT_ROUTE)

            // 动态添加路由
            userStore.routers.forEach(route => {
                router.addRoute('root', route);
            })
            // if(to.name && router.hasRoute(to.name)){
            //     next({...to, replace: true})
            // }else{
            //     next('/404')
            // }
            next(to)
        }
    } else {
        if (to.path === loginPath) {
            next()
        } else {
            next({ path: loginPath, query: { redirect: to.fullPath } })
        }
    }
});

export default router;